/**
 * Created by XianTao on 2016/8/14
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.smartspring.activiti.restcontroller;

import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.rest.common.application.ContentTypeResolver;
import org.activiti.rest.service.api.RestResponseFactory;
import org.activiti.rest.service.api.repository.DeploymentResourceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
public class DeploymentResourceResourceV2 {
    @Autowired
    protected RestResponseFactory restResponseFactory;
    @Autowired
    protected ContentTypeResolver contentTypeResolver;
    @Autowired
    protected RepositoryService repositoryService;

    public DeploymentResourceResourceV2() {
    }

    @RequestMapping(
            value = {"/v2/repository/deployments/{deploymentId}/resources/**"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    public DeploymentResourceResponse getDeploymentResource(@PathVariable("deploymentId") String deploymentId, HttpServletRequest request) {
        Deployment deployment = (Deployment)this.repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
        if(deployment == null) {
            throw new ActivitiObjectNotFoundException("Could not find a deployment with id \'" + deploymentId + "\'.");
        } else {
            String pathInfo = request.getPathInfo();
            if (StringUtils.isEmpty(pathInfo)) {
                pathInfo = request.getServletPath();
            }
            String resourceName = pathInfo.replace("/v2/repository/deployments/" + deploymentId + "/resources/", "");
            List resourceList = this.repositoryService.getDeploymentResourceNames(deploymentId);
            if(resourceList.contains(resourceName)) {
                DeploymentResourceResponse response = this.restResponseFactory.createDeploymentResourceResponse(deploymentId, resourceName, this.contentTypeResolver.resolveContentType(resourceName));
                return response;
            } else {
                throw new ActivitiObjectNotFoundException("Could not find a resource with id \'" + resourceName + "\' in deployment \'" + deploymentId + "\'.");
            }
        }
    }
}
